package org.example.impl;

//import jdk.nashorn.internal.runtime.logging.Logger;
//import org.apache.ibatis.logging.Log;
//import org.apache.ibatis.logging.LogFactory;
//import org.example.platform.common.exception.BusinessException;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.example.common.exception.BusinessException;
import org.example.mapper.SysDao;
import org.example.service.SysService;
        import org.example.dto.SysDto;
        import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;


//@Logger
@Service
//@AllArgsConstructor
public class SysServiceImpl implements SysService {
    @Resource
    SysDao sysDao;
//    Log log = LogFactory.getLog(SysServiceImpl.class);


    @Override
    public List<SysDto> queryList() throws InterruptedException, ExecutionException {
        List<SysDto> list = new ArrayList<>();
        int sum = sysDao.queryCount();
        int num = 3000;
        int time = sum/num +1;

//         先查询出数据总数量
//         循环总数量，定义线程，并使用CountDownLatch.countDown()递减计数器，最后用await校验是否所有线程都已执行完成，并返回数据
//        CountDownLatch cd = new CountDownLatch(time);
        CompletableFuture<List<SysDto>> cf1= null;
        for(int i=0;i<time;i++){
//            int finalI = i;
//            Thread thread1 = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    list.addAll(sysDao.queryList(finalI != 0 ?finalI*num-num+1 :finalI,num));
//                    System.out.println(list.size());
//                    cd.countDown();
//                }
//            });
//            thread1.start();


            int finalI = i;
            cf1= CompletableFuture.supplyAsync(()->{
                return sysDao.queryList(finalI != 0 ? finalI *num-num+1 : finalI,num);
            });
            list.addAll(cf1.get());
        }
//         cd.await();
        return list;
    }

    @Override
    public List<SysDto> queryList1()  {
        List<SysDto> list = sysDao.queryList1();
        return list;
    }


    @Override
    public void addUserList(SysDto sysDto) {
        sysDao.addUserList(sysDto);
    }

    @Override
    public String exception() {
        throw new BusinessException("自定义异常");
//        return null;
    }

    @SentinelResource("HelloWorld")
    public void helloWorld() {
        // 资源中的逻辑
        System.out.println("hello world");
    }
}
